// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database();
const compareCollect = db.collection('compare')
const userCollect = db.collection('uni-id-users')

const path = require('path');
const fs = require('fs');
const axios = require('axios');
const Jimp = require("jimp");

module.exports = {
	_before: function() { // 通用预处理器

	},
	// async compareImgByTecent({
	// 	path1,
	// 	path2
	// }) {
	// 	// 云市场分配的密钥Id
	// 	const secretId = "AKIDOfeqbKixrAYWyJK2Lakboal0wsXl27A1Pbvg";
	// 	// 云市场分配的密钥Key
	// 	const secretKey = "71T0TnAlgzamDFl8oFz0AP1PHDD9gB3It7CrQC0q";
	// 	const source = "market";
	// 	// 签名
	// 	const datetime = (new Date()).toGMTString();
	// 	const signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
	// 	const sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
	// 	const auth = 'hmac id="' + secretId +
	// 		'", algorithm="hmac-sha1", headers="x-date x-source", signature="' +
	// 		sign + '"';

	// 	// 查询参数(GET)
	// 	const queryParams = {
	// 		"image1": path1,
	// 		"image2": path2
	// 	}
	// 	// body参数（POST方法下）
	// 	// const bodyParams = {}
	// 	// if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
	// 	//     options['body'] = querystring.stringify(bodyParams);
	// 	//     options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
	// 	// }
	// 	// url参数拼接
	// 	let url = "https://service-32nzl94b-1309918647.sh.apigw.tencentcs.com/release/cv/compare";
	// 	if (Object.keys(queryParams).length > 0) {
	// 		url += '?' + querystring.stringify(queryParams);
	// 	}
	// 	const res = await uniCloud.httpclient.request(url, {
	// 		method: 'GET',
	// 		headers: {
	// 			"X-Source": source,
	// 			"X-Date": datetime,
	// 			"Authorization": auth,
	// 			"Accept": "application/json"
	// 		},
	// 		contentType: 'json', // 指定以application/json发送data内的数据
	// 		dataType: 'json' // 指定返回值为json格式，自动进行parse
	// 	})
	// 	console.log(res)
	// 	return res
	// },
	async compareImgBySSIM({
		url1,
		url2
	}) {
		const path1 = path.join(__dirname, 'image1.jpg');
		const path2 = path.join(__dirname, 'image2.jpg');
		const file1 = fs.createWriteStream(path1)
		const file2 = fs.createWriteStream(path2);
		try {
			const response1 = await axios.get(url1, {
				responseType: 'stream'
			})
			response1.data.pipe(file1);
		} catch (e) {
			console(e)
		}
		try {
			const response2 = await axios.get(url2, {
				responseType: 'stream'
			})
			response2.data.pipe(file2);
		} catch (e) {
			console(e)
		}
		// 读取两张图片
		const img1 = fs.readFileSync(path1);
		const img2 = fs.readFileSync(path2);
		// 计算两张图片的相似度
		const similarity = await ssim(img1, img2);
		console.log(`Image similarity: ${similarity}`);
		fs.unlinkSync(path1);
		fs.unlinkSync(path2);
		return similarity;
	},
	async compareImgByHash({
		url1,
		url2
	}) {
		const response1 = await axios.get(url1, {
			responseType: 'arraybuffer'
		})
		const response2 = await axios.get(url2, {
			responseType: 'arraybuffer'
		})
		const buffer1 = Buffer.from(response1.data)
		const buffer2 = Buffer.from(response2.data)
		const img1 = await Jimp.read(buffer1)
		const img2 = await Jimp.read(buffer2)
		// 调整图片大小，确保它们大小相同
		img1.resize(256, 256).deflateLevel(9)
		img2.resize(256, 256).deflateLevel(9)
		// 计算两张图片的像素差异
		const distance = Jimp.distance(img1, img2);
		// 计算两张图片的相似度
		const similarity = 1 - distance;
		console.log(distance, similarity)
		return similarity;
	},
	compareImgBySharp({
		url1,
		url2
	}) {
		// 下载图片1和图片2
		return Promise.all([
				axios.get(url1, {
					responseType: 'arraybuffer'
				}),
				axios.get(url2, {
					responseType: 'arraybuffer'
				})
			])
			.then(([image1Response, image2Response]) => {
				// 将图像1和图像2加载到Sharp中
				return Promise.all([
						sharp(image1Response.data).grayscale().raw().toBuffer(),
						sharp(image2Response.data).grayscale().raw().toBuffer()
					])
					.then(([image1Data, image2Data]) => {
						// 将图像数据转换为数组
						const imageData1 = Array.from(image1Data);
						const imageData2 = Array.from(image2Data);
						// console.log(imageData1, imageData2)
						// 计算两张图片的差异值
						const diff = imageData1.reduce((acc, cur, index) => {
							return acc + Math.abs(cur - imageData2[index]);
						}, 0);
						// 计算图片相似度
						const similarity = 1 - (diff / (imageData1.length * 255));
						console.log('图片相似度为：', similarity);
						return Math.round(similarity * 100) / 100
						//如果需要更准确的结果，建议使用更复杂的图像特征提取算法
					})
					.catch(err => console.error(err));
			})
			.catch(err => console.error(err));
	},
	async getSelfScore({
		pageNum,
		pageSize
	}) {
		const token = this.getUniIdToken()
		const user = await userCollect.where({
			token
		}).get()
		console.log('getSelfScore: ', user)
		const res = await compareCollect.where({
			username: user.data[0].username
		}).skip((pageNum - 1) *
			pageSize).limit(pageSize).get()
		return res
	},
	async getAllScore({
		pageNum,
		pageSize
	}) {
		const res = await compareCollect.skip((pageNum - 1) * pageSize).limit(pageSize).get()
		return res
	},
	async add({
		score
	}) {
		const token = this.getUniIdToken()
		const clientInfo = this.getClientInfo()
		const user = await userCollect.where({
			token
		}).get()
		const res = await compareCollect.add({
			score,
			username: user.data[0].nickname
		})
		return res
	}
}